#include "expresstrack.h"
#include "ui_expresstrack.h"

ExpressTrack::ExpressTrack(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::ExpressTrack)
{
    ui->setupUi(this);

    isEdit=true;
    table=TD_EXPRESS_TRACK;
    model=new QSqlTableModel(this);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    ui->tableView->setModel(model);
    ui->tableView->setEditTriggers(QTableView::DoubleClicked);

    createMenu();
    updateView();
}

ExpressTrack::~ExpressTrack()
{
    delete ui;
}

void ExpressTrack::generateMenu()
{
    menu->addAction(QStringLiteral("新增... (F1)"),this,&ExpressTrack::newItem);
    menu->addAction(QStringLiteral("更新视图 (F5)"),this,&ExpressTrack::updateView);
    menu->addSeparator();
    menu->addAction(QStringLiteral("已完成"),this,&ExpressTrack::en_finish);
    menu->addAction(QStringLiteral("撤销 (Ctrl+Z)"),this,&ExpressTrack::revert);
    menu->addAction(QStringLiteral("保存 (Ctrl+S)"),this,&ExpressTrack::save);
    menu->addSeparator();
    QMenu *m_option=menu->addMenu(QStringLiteral("选项"));
    m_option->addAction(QStringLiteral("删除 (Delete)"),this,&ExpressTrack::removeItem);
}

void ExpressTrack::updateView()
{
    model->setTable(table);
    model->setFilter("addition != '已完成'");
    model->select();
    setHeaderData();
}

void ExpressTrack::setHeaderData()
{
    ui->tableView->hideColumn(0);   //id
    model->setHeaderData(1,Qt::Horizontal,QStringLiteral("日期"));
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("商品信息"));
    ui->tableView->setColumnWidth(2,240);
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("快递信息"));
    ui->tableView->setColumnWidth(3,240);
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("最新状态"));
}

void ExpressTrack::newItem()
{
    ET_AddItem itemAdd;
    if(itemAdd.exec() == QDialog::Accepted)
        updateView();
}

void ExpressTrack::en_finish()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(!index.isValid())
        return;

    int id=sp_fetchId(index);
    if(sp_updateColumnById(table,"addition","已完成",id))
        updateView();
}

void ExpressTrack::removeItem()
{
    QModelIndex index=ui->tableView->currentIndex();
    if(index.isValid())
        model->removeRow(index.row());
}
